<template>
	<div class="create">
		<!--<div style="position: fixed;top: 0;left: 0;right: 0;z-index: 99;">
			<div class="padd"></div>
			<div class="header">
				<div class="back-icon" @click="goBack">
					<div class="iconfont-back">
						<div class="iconfont">&#xe624;</div>
					</div>
				</div>
				<div class="title">创建管理</div>
			</div>
		</div>-->
		<div class="up-warrp">		
			<div class="upload_imgs" id="uploadImgs" @click.stop="autoClick">
				<img v-if="lenImg===0" id="showImg" src="../../../assets/images/groups/upload.jpg" />								
				<img v-if="imgU" id="showImg" :src="imgU" />								
				<input type="file" @change="onFileChange" style="display:none;" id="upfile">
			</div>
		</div>
	    <group label-width="5.5em" label-margin-right="2em">
	    	<x-textarea  title="活动名称" v-model.trim="name" placeholder="请输入活动名称" :show-counter="false" :rows="1" value-text-align="right"></x-textarea>
	    	<datetime style="text-decoration: none;" :min-hour="minHours" :start-date="minDate" format="YYYY-MM-DD HH:mm" title="开始时间" v-model="startTime" value-text-align="right"></datetime>
	    	<datetime style="text-decoration: none;" format="YYYY-MM-DD HH:mm" :min-hour="minHours" :start-date="minEndTime" title="结束时间" v-model="endTime" value-text-align="right"></datetime>	      	
	    	<popup-radio  title="活动地点" :options="didianLsit" v-model="didian">
	    </popup-radio>  
	    	<div v-show="didian==='线下'">
	    		<x-address title="选择区域" v-model="address" :list="newAddressData"></x-address>
				<x-textarea title="详细地址" v-model.trim="detail" placeholder="请填写详细信息" :show-counter="false" :rows="1"></x-textarea>
	   		</div>
	    </group>
	    <div class="address vux-1px-b" @click="handleTitle">
	    	<div class="address-title">标签</div>
	    	<div class="address-text">{{this.titleText}}</div>	    	  
	    	<div class="iconfont">&#xe62d;</div>
	    </div>
		
	    <group label-width="5.5em" label-margin-right="2em" >
	    	<popup-radio  title="活动类别" :options="activityOptions" v-model="activityType">
	    	</popup-radio>  
	    	<cell
		      title="详细信息"
		      :border-intent="false"
		      :arrow-direction="showContent004 ? 'right' : 'down'"
		      @click.native="showContent004 = !showContent004"></cell>
	    </group>
	    
      	
		<div class="edit-con" :class="showContent004?'animate':''">
			<quill-editor 
      			v-model="content" 
      			ref="myQuillEditor" 
      			:options="editorOption" 
   			>
    		</quill-editor>
		</div>
	    <group label-width="5.5em" label-margin-right="2em" >	    	
	    	<popup-radio  title="报名方式" :options="enrollOption" v-model="enrollType">
	    		<p slot="popup-header" class="vux-1px-b demo3-slot" style="text-align: center;padding: 8px 0;color: #888;">请选择</p>
	    	</popup-radio>
	    	<x-textarea  title="最大人数" v-model.trim="maxPeople" placeholder="请输入活动最大人数" :show-counter="false" :rows="1" value-text-align="right"></x-textarea>
	    	<x-textarea v-show="enrolltype" title="报名价格" v-model.trim="price" placeholder="请输入活动的金额" :show-counter="false" :rows="1" value-text-align="right"></x-textarea>
	    </group>     
      	<div class="confirm-btn" @click="submitVal">发布活动</div>
      	
      	<a-title v-show="titleShow" :title="titleList" @close="closeTitle"></a-title>
	</div>
</template>

<script type="text/javascript">
	import {getUrlParam}  from '@/assets/js/getUrlParam'
	import { setCookie, getCookie, removeCookie, clearCookie } from '@/assets/js/cookie'
	import ATitle from './components/title'
	import { PopupRadio , GroupTitle, Group, Cell, XInput, Selector, PopupPicker, Datetime, XNumber, ChinaAddressV4Data, XAddress, XTextarea, XSwitch } from 'vux'
	export default{
		name : 'createActivity',
		data(){
			return{
				showContent004:false , //富文本的显示
		        startTime: '请选择开始时间',	//活动开始时间
		        endTime: '请选择结束时间',	//活动结束时间	        
		        activityOptions:[], //活动类型列表		        
		        activityType:'',
		        name:'',
		        enrollOption:['付费报名','免费报名'],  //报名方式
		        enrollType:'',	//报名方式
		        price:'',		//报名价格
		        titleShow:false,
		        typeActivity:[],
		        type:'',
		        value:'',
		        maxPeople:'' ,//最大人数
		        titleList:[],//标签集合
		        titles:[],//所选标签集合
		        picValue:{},
		        serverData:{},
		        didianLsit:['线上','线下'],
		        didian:'',
		        address:[],
		        addressData:[],
		        detail:'',
		        content:'',	//相信信息-富文本编辑内容
		        editorOption:{
		        	modules:{
                        toolbar:[
                          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
                          ['blockquote', 'code-block'],
                          ['link', 'image','color']
                        ]
                    }
		        },	//富文本编辑参数
				images : [],
				params : {
					
				},
				max : 1,
				lenImg : 0,
				imgU : '',
				uploadOkUrl : '',
				minDate : '',
				minEndTime : ''
			}
		},
		mounted(){
			this.getCityList()
			this.getNowTime()
		},
		methods:{
			//返回到上一页
			goBack(){
				this.$router.go(-1)
			},
			//提交表单数据
			submitVal(){
				let activityTypeId = ''
				let address = ''
				this.address.forEach( item => {
					if(item === "110019" || item === "120111" || item === "310111" || item === "500111"){
						item = ''
					}
					if(item){
						address += item+';'
					}					
				})
				address += this.detail
				this.serverData.activityType.forEach(item =>{
					if(item.type_name === this.activityType){
						activityTypeId = item.id
					}
				})
				let activityInfo = {
					uploadOkUrl :this.uploadOkUrl,
					vid 		:getUrlParam('user_product_id') || '',    //服务好ID
					title  		:this.name,
					begin_time  :this.startTime,
					end_time  	:this.endTime,
					address     :address,
					content     :this.content,
					tagId		:this.titles.join(';'),
					otype       :this.didian === '线上' ? 0 : 1,
					apply_type  :activityTypeId,
					limit_numb  :this.maxPeople ,
					is_free  	:this.enrollType,
					price       :this.price,
					userinfo :{
						uid   : getUrlParam('uid')   || '',
						token : getUrlParam('token') || '',
					}
				}
				this.enrollType === '免费报名'  ? delete activityInfo.price     : activityInfo
				this.didian     === '线上'	  ? delete activityInfo.address  : activityInfo
				let validateResult = this.validateForm()
				console.log(activityInfo)
				if(validateResult.status){
					this.$vux.loading.show({text: '正在创建'})
					this.$axiosPost('/api/activity/creatActivity',{
						data : JSON.stringify(activityInfo)
					}).then((res)=>{
						this.$vux.loading.hide()
						if(res.status === 1){
							this.$vux.toast.text('活动创建成功', 'top')
							this.$router.push('/activityManagement')
						}else{
							this.$vux.toast.text('活动创建失败', 'top')
						}
					})
				}else{
					this.$vux.toast.text(validateResult.msg, 'top')
				}				
			},
			//获取城市列表
			getCityList(){
				this.$axiosGet('/api/activity/creatIndex',{
					params:{
						userinfo :{
							uid   : getUrlParam('uid')   || '',
							token : getUrlParam('token') || '',
						}
					}
				}).then( (res) => {
					if(res){
						this.serverData = res
						this.addressData = res.area
						if(res.activityType){
							res.activityType.forEach(item =>{
								this.activityOptions.push(item.type_name)
							})
						}
					}else if(res.status === 404){
						this.$vux.toast.text(res.msg || '请求异常', 'top')
					}
					
				})
			},
			//打开活动标签组件
			handleTitle(){
				this.titleShow = true
				this.$axiosGet('/api/activity/activityTag',{
					params:{
						userinfo :{
							uid   : getUrlParam('uid')   || '',
							token : getUrlParam('token') || '',
						}
					}
				}).then((res) => {
					if(res){
						this.titleList = res
					}
				})
			},
			//关闭活动标签组建
			closeTitle(titles){
				if(!titles){
					this.titleShow = false
					return
				}
				this.titles = titles
				this.titleShow = false
			},
			//自动点击
			autoClick() {				
				document.getElementById("upfile").click();				
				document.getElementById("upfile").click();				
			},			
			//上传文件
			onFileChange($event) {		
				let self = this;			
				this.lenImg = $event.target.files.length;
				if(this.lenImg === 0) {
					return;
				}		
				let fileArr = $event.target.files;
				var file=fileArr[0];
				var reader = new FileReader();				                       		                       
		            reader.onload = function (e) {	
		            	self.imgU = e.target.result;		            	
		            	self.$axiosPostno('/utils/files/uploadbase64.json',{
		            		upload : self.imgU
				        }).then(res=>{
				        	if(res.code == 200){
				        		self.uploadOkUrl = res.data.fullpath
				        	}
				        })
		            }
		            reader.readAsDataURL(file);
	
		            

			},
			getNowTime(){
				let oDate = new Date()
				let years = oDate.getFullYear()
				let month = oDate.getMonth() + 1
				if(month < 10){
					month = '0' + month
				}
				let day   = oDate.getDate()
				if(day < 10){
					day = '0' + day
				}
				this.minDate = years + '-' + month + '-' + day
			},
			validateForm(){
				let result = {
					status : false,
					msg    : ''
				}
				if(!this.imgU){
					result.msg = '请选择活动封面'
					return result
				}
				if(!this.name){
					result.msg = '请输入活动名称'
					return result
				}
				if(this.startTime === '请选择开始时间'){
					result.msg = '请选择活动开始时间'
					return result
				}
				if(this.endTime === '请选择结束时间'){
					result.msg = '请选择活动结束时间'
					return result
				}
				if(this.startTime >= this.endTime){
					result.msg = '活动开始时间要早于结束时间'
					return result
				}
				if(!this.didian){
					result.msg = '请选择活动地点'
					return result
				}
				if(this.didian === '线下'){
					if(this.address.length === 0){
						result.msg = '请选择城市'
						return result
					}
					if(!this.detail){
						result.msg = '请输入详细地址'
						return result
					}
				}
				if(this.titles.length === 0){
					result.msg = '请选择活动标题'
					return result
				}
				if(!this.activityType){
					result.msg = '请选择活动类别'
					return result
				}
				if(!this.content){
					result.msg = '请输入活动详细信息'
					return result
				}
				if(!this.enrollType){
					result.msg = '请选择报名方式'
					return result
				}
				if(!this.maxPeople){
					result.msg = '请输入活动人数上限'
					return result
				}
				if(this.enrollType === '付费报名'){
					if(!this.price){
						result.msg = '请输入活动价格'
						return result
					}
				}
				result.msg 	  = '验证成功'
				result.status = true
				return result
			}
		},
		watch:{
			endTime(){
				if(this.startTime !== '请选择开始时间'){
					if(this.startTime >= this.endTime){
						this.$vux.toast.text('活动开始时间要早于结束时间','top')
					}
				}
			},
			startTime(){
				if(this.startTime !== '请选择开始时间'){
					this.minEndTime = this.startTime.substr(0,10)
				}		
			}
		},
		computed:{
			enrolltype(){
				if(this.enrollType === '免费报名'){
					return false
				}
				if(this.enrollType === '付费报名'){
					return true
				}				
			},
			titleText(){
				let title = ''
				this.titleList.forEach( item => {
					if(item.tag_son instanceof Array){
						item.tag_son.forEach( items => {
							if(items.id === this.titles[0]){
								title = items.title + '...'
							}
						})
					}

				})
				return title
			},
			minHours(){
				let oDate = new Date()
				let hours = oDate.getHours()
				if( hours < 10){
					hours = '0' + hours
				}
				return hours
			},
			newAddressData(){
				this.addressData.forEach(item=>{
					if(item.parent === "110000"){
						item.parent = "110019"
					}
					if(item.parent === "120000"){
						item.parent = "120111"
					}
					if(item.parent === "310000"){
						item.parent = "310111"
					}
					if(item.parent === "500000"){
						item.parent = "500111"
					}
				})
				this.addressData.push({
					name : "市辖区",
					parent : "110000",
					value  : "110019"
				})
				this.addressData.push({
					name : "市辖区",
					parent : "120000",
					value  : "120111"
				})
				this.addressData.push({
					name : "市辖区",
					parent : "310000",
					value  : "310111"
				})
				this.addressData.push({
					name : "市辖区",
					parent : "500000",
					value  : "500111"
				})
				return this.addressData
			}
		},
		components:{
			Group,
	        GroupTitle,
	        Cell,
	        XInput,
	        Selector,
	        PopupPicker,
	        XAddress,
	        Datetime,
	        XNumber,
	        XTextarea,
	        XSwitch,
	        PopupRadio,
	        ATitle
		}

	}
</script>
<style lang="less" scoped>
	@import '~vux/src/styles/1px.less';
	.create{
		text-align: left;
		.padd{
			height:.54rem;
			background:#ff1351;
		}
		.header{
			position: relative;
			display:flex;
			height:.9rem;
			line-height: .9rem;
			color:#fff;
			background:#ff1351;
			font-size:.34rem;		
			.iconfont-back{
				position: absolute;
				left: .0rem;
				top: .0;
				height: .6rem;
				color: #fff;
				.iconfont{
					padding-left:.17rem;
				}
			}
			.title{
				flex:1;
				text-align: center;
			}
		}

		.up-warrp{
			overflow: hidden;
			width: 100%;
			height: 3.8rem;
			background: #fff;
			.upload_imgs {
				width: 80%;	
				height: 2.4rem;	
				padding: 1rem 0;						
				margin: 0 auto;
				margin-top: .7rem;
				border: 2px dashed #b3b3b3;
				border-radius: .3rem;
				display: flex;
				flex-flow: wrap;				
				align-items: center;	
				position: relative;			
				#showImg {					
					width: 1.54rem;
					height: 1.54rem;
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%,-50%);
				}
			}
		}
		.edit-con{
  			overflow: hidden;
			background: #fff;
			max-height: 0;
			transition: max-height .5s cubic-bezier(0, 1, 0, 1) -.1s
		}
		.activity-name{
			overflow: hidden;
			display: flex;
			margin-top: .2rem;
			height: 1rem;
			background: #fff;
			.activity-title{
				flex: 1;
				.title,.length{
					display: inline-block;
					color: #a4a4a4;
					line-height: 1rem;
				}
				.title{
					padding-left: .26rem;
					font-size: .45rem;
				}
				.length{
					margin-left: .32rem;
					font-size: .28rem;
				}
			}
			.title-icon{
				margin-top: .18rem;
				height: .64rem;
				width: .64rem;
				line-height: .64rem;
				text-align: center;
				margin-right: .26rem;
				background: #f5f5f5;
				border-radius: 50%;
				font-size: .34rem;
			}
		}
		
		.address{
			display: flex;
			position: relative;
			padding: 0 .3rem;
			height: .88rem;
			line-height: .88rem;
			background: #fff;
			font-size: .34rem;
			.address-title{
				flex: 1;
			}
			.address-text{
				padding-right: .3rem;
				flex: 1;
				text-align: right;
				color: rgb(153,153,153);
			}
			.iconfont{
				position: absolute;
				right: .3rem;
				top: 0;
				text-align: right;
				font-size: .24rem;
				color: #C8C8CD;
			}
		}
		.confirm-btn{
			height: 1.25rem;
			background: #ff1351;
			font-size: .4rem;
			text-align: center;
			line-height: 1.25rem;
			color: #fff;
		}
		.animate {
		  max-height: 9999px;
		  transition-timing-function: cubic-bezier(0.5, 0, 1, 0);
		  transition-delay: 0s;
		}
		

	}
</style>